package dk.pun.aot.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

import dk.pun.aot.client.resource.GlobalResource;
import dk.pun.aot.client.widget.SplashPanel;
import dk.pun.aot.shared.user.LoginInfo;

public class AlphaOmegaTools implements EntryPoint {

	public void onModuleLoad() {
		GWT.<GlobalResource>create(GlobalResource.class).css().ensureInjected();
		
		final LoginServiceAsync loginService = GWT.create(LoginService.class);
		if (AnonymousLogin.isLoggedIn()) {
			loginService.anonymousLogin(new AsyncCallback<LoginInfo>() {
				
				@Override
				public void onFailure(Throwable caught) {
					Window.alert("Failed to login anonymously: " + caught.getMessage());
					GWT.log("Failed to login anonymously: ", caught);
				}

				@Override
				public void onSuccess(LoginInfo result) {
					loadController(result);
				}						
			});
		} else {
			loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
				
				@Override
				public void onFailure(Throwable caught) {
					Window.alert("Failed to login: " + caught.getMessage());
					GWT.log("Failed to login: ", caught);
				}
				
				@Override
				public void onSuccess(LoginInfo result) {
					if (result.isLoggedIn()) {
						loadController(result);
					} else {
						loadLogin(result);
					}
				}
			});
		}
	}
	
	private void loadController(LoginInfo loginInfo) {
		AlphaOmegaToolsServiceAsync rpcService = GWT.create(AlphaOmegaToolsService.class);
		HandlerManager eventBus = new HandlerManager(null);
		Controller controller = new Controller(loginInfo, rpcService, eventBus);
		controller.go(RootPanel.get());
	}

	private void loadLogin(LoginInfo loginInfo) {
		RootPanel.get().add(new SplashPanel(loginInfo.getLoginURL()));
	}
}
